package com.zhy.baselibrary.mqtt


import com.zhy.baselibrary.utils.Klog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
import org.eclipse.paho.client.mqttv3.MqttCallback
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence

class MqttManager {
    companion object {
        private const val brokerUrl = "tcp://broker.emqx.io:1883" // 公共测试服务器
        private val clientId: String = MqttClient.generateClientId()
        private val viewModelScope = CoroutineScope(Dispatchers.Main)
        var mqttManager: MqttManager? = null
        private val client by lazy {
            MqttClient(brokerUrl, clientId, MemoryPersistence())
        }

        init {
            mqttManager = MqttManager()
        }

        fun init(): MqttManager {
            return mqttManager!!
        }
    }

    fun connect(): MqttManager {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val callback = object : MqttCallback {
                    override fun connectionLost(cause: Throwable?) {
                        Klog.d("-------connectionLost------------", "断开连接")
                    }

                    override fun messageArrived(topic: String?, message: MqttMessage?) {
                        Klog.d("------messageArrived------ ", message?.toString() ?: "null")
                    }

                    override fun deliveryComplete(token: IMqttDeliveryToken?) {
                        Klog.d("-------deliveryComplete------------", "消息发送成功回调")

                    }
                }
                client.setCallback(callback)
                val options = MqttConnectOptions()
                options.isCleanSession = true // 清除旧会话
                options.setConnectionTimeout(10)// 设置超时时间
                options.setKeepAliveInterval(20) // 心跳间隔
                options.isAutomaticReconnect = true // 自动重连
                client.connect(options)
            }
        }
        return mqttManager!!
    }

    fun subscribe(topic: String): MqttManager {
        if(client.isConnected){
            client.subscribe(topic, 1) // QoS 1：至少一次传递
        }else{
            Klog.d("-------subscribe---------", "未连接")
        }
        return mqttManager!!
    }

    fun publish(topic: String, payload: String): MqttManager {
        if(client.isConnected){
            val message = MqttMessage(payload.toByteArray())
            message.qos = 1 // 设置QoS级别
            client.publish(topic, message)
        }else{
            Klog.d("------publish--------", "未连接")
        }
        return mqttManager!!
    }

    fun disconnect() {
        if (client.isConnected) {
            client.disconnect()
            client.close()
        }
    }
}